#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <memory>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "Log.hpp"
#include "InetAddr.hpp"

namespace socket_ns {
    using namespace log_ns;

    enum {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR
    };

    const int gblcklog = 8;

    class TcpSocket;
    class Socket;
    using ScokSPtr = std::shared_ptr<Socket>;

    // 模板方法模式
    class Socket {
    public:
        Socket() {}
        ~Socket() {}

        virtual int CreateSocketOrDie() = 0;
        virtual void CreateBindOrDie(uint16_t port) = 0;
        virtual void CreateListenOrDie(int blcklog = gblcklog) = 0;
        virtual int CreateAccepte(InetAdrr* addr) = 0;
        virtual bool CreateConnector(uint16_t server_port, std::string server_ip) = 0;
    
        virtual ssize_t Recv(std::string* out) = 0;
        virtual ssize_t Send(std::string& in) = 0;
        virtual int GetSockfd() = 0;
        virtual void Close() = 0;
        virtual void ReUseAddr() = 0;
    public:
        void BuildListenSocket(uint16_t port, int blcklog = gblcklog) {
            // 分别是创建sockfd，然后将其绑定，然后listen
            CreateSocketOrDie();
            ReUseAddr();
            CreateBindOrDie(port);
            CreateListenOrDie(blcklog);
        }

        bool BuildCilentSocket(uint16_t server_port, std::string server_ip) {
            // 分别是创建sockfd，然后绑定，然后connnect
            CreateSocketOrDie();
            return CreateConnector(server_port, server_ip);
        }
    };


    class TcpSocket : public Socket {
    public:
        TcpSocket() {}

        TcpSocket(int sockfd)
            : _sockfd(sockfd)
        {}

        // 创建 sockfd
        int CreateSocketOrDie() override {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0) {
                LOG(FATAL, "create sockfd fail\n");
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "get listensockfd success, sockfd: %d\n", _sockfd);
            return _sockfd;
        }


        // 绑定
        void CreateBindOrDie(uint16_t port) override {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;

            int bind_n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
            if (bind_n < 0) {
                LOG(FATAL, "bind listensockfd fail, the reason: %s\n", strerror(errno));
                exit(BIND_ERROR);
            }
            LOG(INFO, "bind success\n");
        }

        // 绑定之后listen
        void CreateListenOrDie(int blcklog = gblcklog) override {
            int n = listen(_sockfd, blcklog);
            if (n < 0) {
                LOG(FATAL, "listen socket fail\n");
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "listen sucess\n");            
        }

        int CreateAccepte(InetAdrr* addr) override {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // std::cout << "start accept" << std::endl;

            int sockfd = accept(_sockfd, (struct sockaddr*)&peer, &len);
            *addr = peer;
            // std::cout << "accept done" << std::endl;
            
            return sockfd;
        }

        bool CreateConnector(uint16_t server_port, std::string server_ip) override {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            socklen_t len = sizeof(server);
            server.sin_family = AF_INET;
            server.sin_port = htons(server_port);
            // server.sin_addr.s_addr = inet_addr(server_ip.c_str());
            inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr);

            int n = connect(_sockfd, (struct sockaddr*)&server, sizeof(server));
            if (n < 0) {
                return false;                
            }
            return true;
        }

        ssize_t Recv(std::string* out) override {
            // 收消息，将收到的信息
            char buff[4096];
            ssize_t n = recv(_sockfd, buff, sizeof(buff), 0);
            if (n <= 0) return n;
            buff[n] = 0;
            *out += buff;
            return n;
        }

        ssize_t Send(std::string& in) override {
            ssize_t n = send(_sockfd, in.c_str(), in.size(), 0);
            return n;
        }

        int GetSockfd() override {
            return _sockfd;
        }

        void Close() override {
            close(_sockfd);
        }

        void ReUseAddr() override {
            int opt = 1;
            setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        }

        ~TcpSocket() {
            // if (_sockfd < 0) close(_sockfd);
        }
    private:
        int _sockfd;
    };
}
